import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import { getArticleListByIdAction, updateArticleListByIdAction } from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';

type Props = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: Props) {
  const { articles } = useAppSelector((state) => state.article);
  const { channel_id: activeId } = useAppSelector((state) => state.channel);
  const { results: list = [], pre_timestamp } = articles[channel_id] || {};

  const dispatch = useDispatch();
  const handleLoadMore = async () => {
    await dispatch(updateArticleListByIdAction({ channel_id, timestamp: pre_timestamp }));
  };

  useEffect(() => {
    if (activeId !== channel_id) return;
    if (list.length) return;
    dispatch(getArticleListByIdAction({ channel_id }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channel_id, dispatch, activeId]);

  const handleRefresh = async () => {
    await dispatch(getArticleListByIdAction({ channel_id }));
  };

  return (
    <PullToRefresh onRefresh={handleRefresh}>
      <div>
        {list.map((item) => {
          return <ArticleItem data={item} key={item.art_id} />;
        })}
        <InfiniteScroll loadMore={handleLoadMore} hasMore={!!pre_timestamp}></InfiniteScroll>
      </div>
    </PullToRefresh>
  );
}
